package com.ruoyi.api.controller;

import com.ruoyi.api.service.SelectSaleService;
import com.ruoyi.audit.domain.Audit;
import com.ruoyi.audit.service.AuditService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.WXShiroUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.company.domain.Company;
import com.ruoyi.company.domain.CompanyOther;
import com.ruoyi.company.domain.CompanyScope;
import com.ruoyi.company.service.ICompanyInvoiceService;
import com.ruoyi.company.service.ICompanyOtherServer;
import com.ruoyi.company.service.ICompanyScopeServer;
import com.ruoyi.company.service.ICompanyServer;
import com.ruoyi.expressdelivery.domain.ExpressDelivery;
import com.ruoyi.expressdelivery.service.ExpressDeliveryService;
import com.ruoyi.product.domain.ProductModel;
import com.ruoyi.productProof.domain.ProductProof;
import com.ruoyi.productProof.service.ProductProofService;
import com.ruoyi.purchase.service.PurchaseOrderService;
import com.ruoyi.sale.domain.SaleorderOrder;
import com.ruoyi.sale.service.ISaleorderService;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 销售订单管理 wx公众号
 */
@RestController
@RequestMapping("/wx/business/selectSale")
public class SelectSaleController extends BaseController {

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private AuditService auditService;

    @Autowired
    private SelectSaleService selectSaleService;

    @Autowired
    private PurchaseOrderService purchaseOrderService;

    @Autowired
    private ISysDictDataService dictDataService;

    @Autowired
    private ICompanyInvoiceService companyInvoice;

     @Autowired
     private ICompanyServer companyServer;

    @Autowired
    private ISaleorderService iSaleorderService;

    @Autowired
    private ProductProofService productProofService;

    @Autowired
    private ICompanyScopeServer companyScopeServer;

    @Autowired
    private ICompanyOtherServer iCompanyOtherServer;

    @Autowired
    private ExpressDeliveryService expressDeliveryService;

    /**
     * 通过字典名，查询字典数据
     *
     * @param dictType 查询条件
     * @return 结果
     */
    @PostMapping("/selectDict")
    @ResponseBody
    public AjaxResult list(String[] dictType) {
        HashMap<Object, List<SysDictData>> map = new HashMap<>();
        SysDictData sysDictData = new SysDictData();
        for (String s : dictType) {
            sysDictData.setDictType(s);
            List<SysDictData> list = dictDataService.selectDictDataList(sysDictData);
            map.put(s, list);
        }
        return AjaxResult.success(map);
    }

    /**
     * 销售订单管理list
     */
    @PostMapping("/selectSale")
    @ResponseBody
    public TableDataInfo showlist(SaleorderOrder saleorderOrder) {
        startPage();
        SysUser sysUser=SecurityUtils.getLoginUser().getUser();
        saleorderOrder.setDeptId(sysUser.getCompanyId());
        //定义查询集合
        if (!sysUser.getDeptId().equals(sysUser.getCompanyId())) {
            saleorderOrder.setSaleorderUserId(sysUser.getUserId());
        }
        List<SaleorderOrder> list = selectSaleService.selectSaleorderOrderList(saleorderOrder);
        return getDataTable(list);
    }
    /**
     * 查看销售订单
     */
    @ResponseBody
    @PostMapping("/lookSelectSale")
    public AjaxResult Look(Long saleorderId) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("saleorderId", saleorderId);
        hashMap.put("deptId", user.getCompanyId());
        SaleorderOrder saleorderOrder = selectSaleService.selectSaleorderById(hashMap);
        return AjaxResult.success(saleorderOrder);
    }

    /**
     * 生成销售订单编号
     */
    @ResponseBody
    @PostMapping("/generateNum")
    public AjaxResult orderNum(Date date, int i) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Map<String, Object> map = new HashMap<>();
        String orderNum = purchaseOrderService.orderNum(date, i);
        if (orderNum.equals("0")) {
            return AjaxResult.error("请先设置订单编号前缀！");
        }
        map.put("orderNum", orderNum);
        map.put("taxRate", companyServer.selectByCompanyId(user.getCompanyId()).getTaxRate());
        return AjaxResult.success(map);
    }

    /**
     * 根据companyId 查询 公司名称
     */
    @PostMapping("/selectDeptNameById")
    @ResponseBody
    public AjaxResult selectDeptNameById(String deptName) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long companyId = user.getCompanyId();
        Map<String, Object> map = new HashMap();
        map.put("deptId", user.getCompanyId());
        if (deptName != null & !"".equals(deptName)) {
            map.put("deptName", deptName);
        }
        if (!user.getDeptId().equals(companyId)) {
            map.put("userId", user.getUserId());
        }
        List<SysUser> sysUsers = iSysUserService.selectSupplierByMap(map);
//        List<SysUser> sysUsers = iSysUserService.selectSupplierById(user.getCompanyId());
        return AjaxResult.success(sysUsers);
    }

    /**
     * 查询产品的型号信息
     *
     * @param productType 查询条件
     * @return 结果
     */
    @PostMapping("/selectProductType")
    @ResponseBody
    public AjaxResult selectProductType(String productType) {
        SysUser user = SecurityUtils.getLoginUser().getUser();

        HashMap map = new HashMap();
        map.put("deptId", user.getCompanyId());
        if (productType != null & !"".equals(productType)) {
            map.put("productType", productType);
        }
        List<ProductModel> productModels = selectSaleService.selectTableList(map);
        return AjaxResult.success(productModels);
    }

    /**
     * 根据 ModelCode查询
     */
    @PostMapping("/selectNewPrice")
    @ResponseBody
    public AjaxResult selectNewPrice(Long productId, String modelCode, Long companyId) {

        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        //先根据 productId 查 该产品的注册证信息
        List<ProductProof> list = productProofService.selectByProductId(productId);

        boolean flag = true;
        for (int i = 0; i < list.size(); i++) {
            ProductProof productProof = list.get(i);
            Long scopeId = productProof.getScopeId();
            //再根据companyId查 对方是否有该经营范围
            HashMap hashMap = new HashMap();
            hashMap.put("scopeId", scopeId);
            hashMap.put("companyId", companyId);
            CompanyScope companyScope = companyScopeServer.selectScopeBySortAndDeptId(hashMap);
            if (companyScope == null) {
                flag = false;
            }
        }
        if (!flag) {
            return new AjaxResult(AjaxResult.Type.OTHER, "客户没有该产品的经营范围");
        }
        companyId = sysUser.getCompanyId();
        HashMap hashMap = new HashMap();
        hashMap.put("productId", productId);
        hashMap.put("modelCode", modelCode);
        hashMap.put("deptId", companyId);
        List<BigDecimal> price = iSaleorderService.selectSaleorderNewPrices(hashMap);
        Map map = new HashMap();
        if (price.size() != 0) {
            BigDecimal bigDecimal = price.get(0);
            String prices = bigDecimal.toString();
            map.put("prices", prices);
            return AjaxResult.success(map);
        } else {
            map.put("prices", 0);
            return AjaxResult.success(map);
        }
    }

    /**
     * 查询供应商的绑定业务员
     */
    @PostMapping("/selectUser")
    @ResponseBody
    public AjaxResult selectUser( Long companyId) {
        Map<String, Object> map = new HashMap<>();
        map.put("deptId", SecurityUtils.getLoginUser().getUser().getDeptId());
        map.put("companyId", companyId);
        CompanyOther companyOther = iCompanyOtherServer.selectByCompanyIdAndDeptId(map);
        if (companyOther != null) {
            return AjaxResult.success(companyOther);
        } else {
            return AjaxResult.error("该公司没有合作单位请设置负责人信息");
        }
    }

    /**
     * 新增保存销售订单
     */
    @PostMapping("/addSale")
    @ResponseBody
    public AjaxResult add(@RequestBody SaleorderOrder saleorderOrder) {
        SysUser sysUser=SecurityUtils.getLoginUser().getUser();
        String saleorderNum = saleorderOrder.getSaleorderNum();
        Long companyId = saleorderOrder.getCompanyId();
        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("saleorderNum", saleorderNum);
        map1.put("companyId", companyId);
        SaleorderOrder saleorderOrder1 = selectSaleService.selectSaleorderByMap(map1);
        if (saleorderOrder1 != null) {
            //使用SimpleDateFormat的parse()方法生成Date
            SimpleDateFormat a = new SimpleDateFormat("yyyy-MM-dd");
            Date dates = null;
            try {
                //dates = a.parse(a.format(new Date()));
                dates = a.parse(a.format(saleorderOrder.getSaleorderDate()));
            } catch (ParseException e) {
                e.printStackTrace();
            }

            String s = purchaseOrderService.orderNum(dates, 1);
            saleorderOrder.setSaleorderNum(s);
        }


        //创建销售订单
        saleorderOrder.setSaleorderStatus("0");
        saleorderOrder.setCreateBy(sysUser.getNickName());

        //查询供应商的绑定业务员
        Map<String, Object> map = new HashMap<>();
        map.put("deptId", sysUser.getCompanyId());
        map.put("companyId", saleorderOrder.getCompanyId());
        CompanyOther companyOther = iCompanyOtherServer.selectByCompanyIdAndDeptId(map);

        saleorderOrder.setDeptId(sysUser.getCompanyId());
//        saleorderOrder.setSaleorderUserId(WXShiroUtils.getUserId());
        Long customerForStaff = companyOther.getCustomerForPerson();
        saleorderOrder.setSaleorderUserId(customerForStaff);

        int i = selectSaleService.insertSaleorder(saleorderOrder);

        if (saleorderOrder.getSaleorderModels() != null) {
            selectSaleService.insertSaleorderModel(saleorderOrder);
        }
        //添加审核订单
        Audit audit = new Audit();
        //销售订单Id
        audit.setOrderId(saleorderOrder.getSaleorderId());
        //登陆人的companyid
        audit.setCompanyId(sysUser.getCompanyId());
        //主表的含税金额
        audit.setTaxAmount(saleorderOrder.getSaleorderTaxamount());
        //业务员id
        audit.setUserId(saleorderOrder.getSaleorderUserId());
        //客户id
        audit.setSupplierId(saleorderOrder.getCompanyId());
        //订单编号
        audit.setOrderNum(saleorderOrder.getSaleorderNum());

        //0为销售订单
        audit.setOrderType("0");
        //状态0为 未审核
        audit.setAuditStatus("0");
        int insertAudit = auditService.insertAudit(audit);

        if (insertAudit >= 1 && i >= 1) {
            return toAjax(1);
        } else {
            return toAjax(-1);
        }
    }

    @PostMapping("/insert")
    @ResponseBody
    public void insert(ExpressDelivery expressDelivery) {

        String creatime = getTime();
        expressDelivery.setCreatetime(creatime);
        String loginname = SecurityUtils.getLoginUser().getUserName();
        expressDelivery.setLoginname(loginname);
        try {
            expressDeliveryService.insert(expressDelivery);

        } catch (Exception e) {

        }
    }

    @PostMapping("/selectcompany")
    @ResponseBody
    public List<ExpressDelivery> selectcompany(HttpServletRequest httpServletRequest) {

        String companyid = httpServletRequest.getParameter("companyId");
        List<ExpressDelivery> list = expressDeliveryService.selectcompany(companyid);
        return list;

    }


    public String getTime() {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd :hh:mm:ss");
        String time = dateFormat.format(date);
        return time;
    }

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = fileName.substring(fileName.indexOf("_") + 1);
            String filePath = RuoYiConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            //判断是否需要删除下载文件
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            AjaxResult.error("下载文件失败", e);
        }
    }

    @GetMapping("/downPdf")
    public void down(String saleorderNum, String purchaseNum, String pdfUrl, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("Aaaaaaaaa");

        String pdfPath = RuoYiConfig.getDownloadPath() + pdfUrl;
        File file = new File(pdfPath);
        OutputStream os = null;
        String fileName = "";
        if (!"".equals(saleorderNum) && saleorderNum != null) {
            fileName = "购销合同" + saleorderNum;
        } else if (!"".equals(purchaseNum) && purchaseNum != null) {
            fileName = "采购合同" + purchaseNum;
        }
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            FileInputStream in = new FileInputStream(file);
            BufferedInputStream bf = new BufferedInputStream(in);
            os = response.getOutputStream();
            response.setContentType("application/pdf");
            response.setHeader("content-Disposition", "attachment;filename=" + fileName + ".pdf");
            byte[] b = new byte[bf.available() + 1000];
            int i;
            while ((i = bf.read(b)) != -1) {
                os.write(b, 0, i);
            }
            os.flush();
        } catch (IOException ignored) {

        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
